import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface UserInfo {
  userId: number
  username: string
  email: string
  phone: string
  nickname: string
  avatar?: string
  gender?: number
  status: number
  lastLoginAt?: string
  createdAt?: string
  updatedAt?: string
}

export interface LoginForm {
  username: string
  password: string
  remember?: boolean
}

export interface RegisterForm {
  username: string
  email: string
  password: string
  confirmPassword: string
  phone?: string
  verificationCode?: string
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string | null>(localStorage.getItem('token'))
  const getUserInfoFromStorage = () => {
    const stored = localStorage.getItem('userInfo')
    if (stored) {
      return JSON.parse(stored)
    }
    // 临时模拟用户数据用于测试
    return {
      userId: 1,
      username: 'testuser',
      email: 'test@example.com',
      phone: '13800138000',
      nickname: '测试用户',
      status: 1,
      createdAt: new Date().toISOString()
    }
  }
  const userInfo = ref<UserInfo | null>(getUserInfoFromStorage())
  const loading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)

  // 登录
  const login = async (loginForm: LoginForm) => {
    loading.value = true
    try {
      // 模拟API调用
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(loginForm),
      })

      if (!response.ok) {
        throw new Error('登录失败')
      }

      const data = await response.json()

      // 保存token和用户信息
      token.value = data.token
      userInfo.value = data.user
      localStorage.setItem('token', data.token)
      localStorage.setItem('userInfo', JSON.stringify(data.user))

      return { success: true, message: '登录成功' }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, message: error instanceof Error ? error.message : '登录失败' }
    } finally {
      loading.value = false
    }
  }

  // 注册
  const register = async (registerForm: RegisterForm) => {
    loading.value = true
    try {
      // 模拟API调用
      const response = await fetch('/api/auth/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(registerForm),
      })

      if (!response.ok) {
        throw new Error('注册失败')
      }

      const data = await response.json()

      return { success: true, message: '注册成功' }
    } catch (error) {
      console.error('注册失败:', error)
      return { success: false, message: error instanceof Error ? error.message : '注册失败' }
    } finally {
      loading.value = false
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    if (!token.value) return

    loading.value = true
    try {
      // 模拟API调用
      const response = await fetch('/api/user/profile', {
        headers: {
          'Authorization': `Bearer ${token.value}`,
        },
      })

      if (!response.ok) {
        throw new Error('获取用户信息失败')
      }

      const data = await response.json()
      userInfo.value = data.user
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果token无效，不要清除登录状态，只是不更新用户信息
      // 这样可以保留localStorage中的数据
    } finally {
      loading.value = false
    }
  }

  // 更新用户信息
  const updateUserInfo = async (updateData: Partial<UserInfo>) => {
    if (!token.value) return { success: false, message: '请先登录' }

    loading.value = true
    try {
      // 模拟API调用
      const response = await fetch('/api/user/profile', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token.value}`,
        },
        body: JSON.stringify(updateData),
      })

      if (!response.ok) {
        throw new Error('更新用户信息失败')
      }

      const data = await response.json()
      userInfo.value = { ...userInfo.value, ...data.user }

      return { success: true, message: '更新成功' }
    } catch (error) {
      console.error('更新用户信息失败:', error)
      return { success: false, message: error instanceof Error ? error.message : '更新失败' }
    } finally {
      loading.value = false
    }
  }

  // 设置用户信息（用于Profile页面更新后同步）
  const setUser = (user: UserInfo) => {
    userInfo.value = user
    localStorage.setItem('userInfo', JSON.stringify(user))
  }

  // 更新用户头像
  const updateAvatar = (avatarUrl: string) => {
    if (userInfo.value) {
      userInfo.value.avatar = avatarUrl
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
    }
  }

  // 修改密码
  const changePassword = async (oldPassword: string, newPassword: string) => {
    if (!token.value) return { success: false, message: '请先登录' }

    loading.value = true
    try {
      // 模拟API调用
      const response = await fetch('/api/user/change-password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token.value}`,
        },
        body: JSON.stringify({ oldPassword, newPassword }),
      })

      if (!response.ok) {
        throw new Error('修改密码失败')
      }

      return { success: true, message: '密码修改成功' }
    } catch (error) {
      console.error('修改密码失败:', error)
      return { success: false, message: error instanceof Error ? error.message : '修改密码失败' }
    } finally {
      loading.value = false
    }
  }

  // 退出登录
  const logout = () => {
    token.value = null
    userInfo.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  // 设置token
  const setToken = (newToken: string) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  // 检查登录状态
  const checkAuthStatus = async () => {
    if (token.value && !userInfo.value) {
      await fetchUserInfo()
    }
  }

  // 从localStorage重新初始化状态
  const initFromStorage = () => {
    const storedToken = localStorage.getItem('token')
    const storedUserInfo = localStorage.getItem('userInfo')

    if (storedToken) {
      token.value = storedToken
    }

    if (storedUserInfo) {
      try {
        const parsedUserInfo = JSON.parse(storedUserInfo)
        userInfo.value = parsedUserInfo
      } catch (e) {
        console.error('解析userInfo失败:', e)
        userInfo.value = null
      }
    }
  }

  return {
    // 状态
    token,
    userInfo,
    loading,

    // 计算属性
    isLoggedIn,

    // 方法
    login,
    register,
    fetchUserInfo,
    updateUserInfo,
    changePassword,
    logout,
    checkAuthStatus,
    setToken,
    setUser,
    updateAvatar,
    initFromStorage,
  }
})
